package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 今日佳人
     */
    public ResponseEntity todayBest() {
        User user = UserHolder.getUser();
        //根据toUserId查询今日佳人
        RecommendUser recommendUser = recommendUserApi.findMaxScoreUser(user.getId());
        //如果不存在。自定义设置一个recommendUser
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(95D);
            recommendUser.setDate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
            recommendUser.setToUserId(user.getId());
            recommendUserApi.save(recommendUser);
        }
        //封装vo
        RecommendUserVO vo = new RecommendUserVO();
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        vo.setFateValue(recommendUser.getScore().intValue());
        return ResponseEntity.ok(vo);
    }

    /**
     * 推荐朋友
     * 问题： 如果查询到的推荐好友不够十个。页面显示不美观
     */
    public ResponseEntity recommendation(RecommendUserQueryVO queryVO) {
        User user = UserHolder.getUser();
        //查询推荐给当前用户的好友列表
        PageResult pageResult = recommendUserApi.findRecommendation(queryVO.getPage(), queryVO.getPagesize(), user.getId());
        //如果未查询到推荐的好友，设置默认值
        List<RecommendUser> items = pageResult.getItems();
        if (items == null || items.size() == 0) {
            Long[] ids = {1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L};
            items = new ArrayList<RecommendUser>();
            for (Long id : ids) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(id);
                recommendUser.setScore(100D - id);
                items.add(recommendUser);
            }
            pageResult.setPagesize(ids.length);
            pageResult.setPages(1);
            pageResult.setCounts(ids.length);
            pageResult.setPage(1);
        }
        //封装vo对象
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            RecommendUserVO vo = new RecommendUserVO();
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
            vo.setFateValue(recommendUser.getScore().intValue());
            voList.add(vo);
        }
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 查看佳人信息
     *
     * @param targetId 佳人id
     * @return RecommendUserVO
     */
    public ResponseEntity personalInfo(Long targetId) {
        Long userId = UserHolder.getUser().getId();
        //1. 查看佳人信息
        UserInfo userInfo = userInfoApi.findById(targetId);
        //2. 查询当前用户和佳人的缘分值
        Integer score = recommendUserApi.findRecommendScore(userId, targetId);
        //3. 封装vo
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        vo.setFateValue(score != null ? score : 95);
        return ResponseEntity.ok(vo);
    }

    /**
     * 查看陌生人问题
     *
     * @param targetUserId 目标用户id
     * @return Question
     */
    public ResponseEntity strangerQuestions(Long targetUserId) {
        Question question = questionApi.findByUserId(targetUserId);
        String result = question != null ? question.getTxt() : "are you ok!";
        return ResponseEntity.ok(result);
    }

    /**
     * 回复陌生人问题
     *
     * @param targetUserId 陌生人id
     * @param reply        回复消息
     * @return null
     */
    public ResponseEntity replyQuestions(Long targetUserId, String reply) {
        Long userId = UserHolder.getUser().getId();
        //1. 查询当前用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2. 查询目标用户的陌生人问题
        Question question = questionApi.findByUserId(targetUserId);
        //3. 封装成环信的消息对象，发送消息给对方
        IMessage message = new IMessage();
        message.setUserId(userId.toString());   //设置自己的id
        message.setNickname(userInfo.getNickname());
        message.setStrangerQuestion(question != null ? question.getTxt() : "are you ready");
        message.setReply(reply);
        huanXinTemplate.sendMessage(targetUserId.toString(), message);
        return ResponseEntity.ok(null);
    }

    /**
     * 搜附近好友
     *
     * @param gender   性别
     * @param distance 距离
     */
    public ResponseEntity searchNear(String gender, Integer distance) {
        Long userId = UserHolder.getUser().getId();
        List<UserLocationDTO> locationDTOList = userLocationApi.searchNear(userId, distance);

        //转换vo
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO userLocationDTO : locationDTOList) {
            UserInfo userInfo = userInfoApi.findById(userLocationDTO.getUserId());
            //排除自身和性别不符合的
            if (userInfo.getId().intValue() == userId) {
                continue;
            }
            if (!userInfo.getGender().equals(gender)) {
                continue;
            }
            NearUserVO vo = new NearUserVO();
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());
            vo.setUserId(userInfo.getId());
            voList.add(vo);
        }
        return ResponseEntity.ok(voList);
    }

    /**
     * 探花，左滑右滑
     *
     * @return
     */
    public ResponseEntity getLeftRight() {
        List<UserInfo> userInfoList = userInfoApi.query();
        List<LeftRightVO> leftRightVO = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            if (userInfo.getId() == UserHolder.getUser().getId()) {
                continue;
            }
            LeftRightVO vo = new LeftRightVO();
            vo.setId(userInfo.getId().intValue());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            vo.setGender(userInfo.getGender());
            vo.setAge(userInfo.getAge());
            vo.setTags(userInfo.getTags().split(","));

            leftRightVO.add(vo);
        }
        return ResponseEntity.ok(leftRightVO);

    }

    /*右滑喜欢*/
    public ResponseEntity love(Long id) {
        Long userId = UserHolder.getUser().getId();
        /*判断当前用户有没有和对方的单项关系  有的话就不要重复添加数据*/
        UserLike quer = userLikeApi.quer(id, userId);
        if (quer != null) {
            return ResponseEntity.ok(null);
        }
        Friend friend1 = friendApi.queryy(id, userId);
        /*判断当前用户有没有和对方的好友关系  有的话就不要重复添加数据*/
        if (friend1 != null) {
            return ResponseEntity.ok(null);
        }
        /*查询对方是否喜欢自己 如果对方也喜欢了自己 删除单向关系 添加好友关系 如果对方没喜欢自己 就添加单向关系*/
        UserLike userLike = userLikeApi.findId(id, userId);
        /*如果为空 说明对方没喜欢自己 添加自己喜欢对方的数据到列表*/
        if (userLike == null) {
            userLike = new UserLike();
            userLike.setLikeUserId(id);
            userLike.setUserId(userId);
            userLike.setCreated(System.currentTimeMillis());
            userLikeApi.insrt(userLike);
            return ResponseEntity.ok(null);
        }
        /*走到这里说明了 对方喜欢了自己 然后自己也喜欢了 对方 需要删除单项喜欢 添加好友关系*/
        userLikeApi.remove(id, userId);
        /*添加双向加好友*/
        Friend friend = new Friend();
        friend.setCreated(System.currentTimeMillis());
        friend.setFriendId(id);
        friend.setUserId(userId);
        friendApi.insert(friend);
        return ResponseEntity.ok(null);
    }

    /*左滑不喜欢*/
    public ResponseEntity unlove(Long id) {
        Long userId = UserHolder.getUser().getId();
        /*查询自己和对方是否有好友关系 如果已经是好友就删除好友关系*/
        Friend friend = friendApi.queryy(id, userId);
        if (friend != null) {
            friendApi.removeFriend(id, userId);
        }
        /*查询自己是否喜欢了当前用户  如果喜欢了 就删除单项喜欢关系*/
        UserLike userLike = userLikeApi.quer(id, userId);
        /*说明没有单项喜欢关系 直接返回null*/
        if (userLike == null) {
            return ResponseEntity.ok(null);
        }
        /*删除单项喜欢关系*/
        userLikeApi.removeId(id, userId);
        return ResponseEntity.ok(null);
    }
}
